import {Component, OnInit, ViewChild} from '@angular/core';
import {CategoryService} from "../category.service";
import {ModalDirective} from "ngx-bootstrap";
import {adSystemApiUrl, AliyunOssOutputUrl, tuikeSystemUrl} from "../../../../config/api";
import {HttpService} from "../../../lib/service/http.service";
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {LoginService} from "../../../lib/service/tuike-login.service";

@Component({
  selector: 'app-configure',
  templateUrl: './configure.component.html',
  styleUrls: ['./configure.component.scss'],
  providers: [CategoryService]
})
export class ConfigureComponent implements OnInit {

  type: string;
  message: string;
  isShow = false;

  addFirName: string; // 增加一级类目名称
  addSecName: string; // 增加二级类目名称
  addThirdName: string; // 增加三级类目名称
  firLevel = [];  // 一级类目列表
  secLevel = [];  // 二级类目
  thirdLevel = [];  // 三级类目
  firId: number;  // 选中的一级类目ID
  secId: number;  // 选中的二级类目ID
  thirdId: number;  // 选中的三级类目ID

  editName: string;  // 修改的类目名称
  editId: number;  // 修改的类目ID
  editLevel: number; // 修改级别
  editParent: number; // 修改类目的父id
  editSort;
  editStatus;
  editPic;

  delId;
  delLevel;
  firAddStatus = false;
  secAddStatus = false;
  thirdAddStatus = false;
  firstLoading = false;
  secLoading = false;
  thirdLoading = false;
  picSizeInfo = '建议100*100px';
  picList = [];
  fileList = [];
  picList2 = [];
  fileList2 = [];
  picList3 = [];
  fileList3 = [];
  picList4 = [];
  fileList4 = [];
  addFirSort: string;
  addSecSort: string;
  addThirdSort: string;
  f1 = ['first_picture', 'second_picture', 'third_picture', 'fourth_picture'];
  submitStatus = false;
  isChange = false;
  canChange = false;
  addFirStatus = '1';
  addSecStatus = '1';
  addThirdStatus = '1';
  addUrl = `${tuikeSystemUrl}/api/v1/admin/category/add_category`;

  canVisit = false;
  canVisit1 = false;
  canVisit2 = false;

  @ViewChild('editModal') public editModal: ModalDirective;
  @ViewChild('delModal') public delModal: ModalDirective;

  constructor(private httpService: HttpService,
              private categoryService: CategoryService,
              private adOssUploadService: AdOssUploadService,
              private loginService: LoginService) {
  }

  ngOnInit() {
    this.canVisit = this.loginService.canVisitCheck('category_add');
    this.canVisit1 = this.loginService.canVisitCheck('category_edit');
    this.canVisit2 = this.loginService.canVisitCheck('category_delete');

    this.getCategoryList(1, 0, 'firLevel');
  }

  // 获取类目列表
  getCategoryList(level: number, parent: number, type: string) {
    switch (level) {
      case 1:
        this.firstLoading = true;
        break;
      case 2:
        this.secLoading = true;
        break;
      case 3:
        this.thirdLoading = true;
        break;
    }
    const url = `${tuikeSystemUrl}/api/v1/admin/category/category_list?level=${level}&parent_id=${parent}&pageSize=200`;
    return this.httpService.httpGetAuth(url)
      .subscribe(
        res => {
          this[type] = res.data;
          if (res.data.length > 0) {
            this[type].map((e, i) => {
              if (e.pic) {
                e.pic.indexOf('?update') != -1 ? e.pic = e.pic.substr(0,e.pic.indexOf('?update')) : '';
                e.pic = `${AliyunOssOutputUrl}/${e.pic}?update=${new Date().getTime()}`;
              }
            })
          }
          switch (level) {
            case 1:
              this.firstLoading = false;
              break;
            case 2:
              this.secLoading = false;
              break;
            case 3:
              this.thirdLoading = false;
              break;
          }
        }
      );
  }

  // 选中类目
  chosedCategory(level: number, id: number) {
    if (level === 1) {
      this.firId = id;
      this.secId = 0;
      this.thirdId = 0;
      this.thirdLevel = null;
      this.getCategoryList(2, id, 'secLevel');
    } else if (level === 2) {
      this.secId = id;
      this.getCategoryList(3, id, 'thirdLevel');
    } else {
      this.thirdId = id;
    }
  }

  // 添加类目
  addCategorySubmit(name: string, level: number, parent: number, sort, status) {
    let data = {category_name: name, level: level, parent_id: parent, sort: sort, status: status};
    if (level === 1) {
      this.uploadImg1('fileList', 1, '添加一级类目成功', data);
    } else if (level === 2) {
      this.uploadImg1('fileList2', 2, '添加二级类目成功', data);
    } else {
      this.uploadImg1('fileList3', 3, '添加三级类目成功', data);
    }
  }

  // 添加类目
  addCategory(e, level: number) {
    e.stopPropagation();
    if (level === 1) {
      this.fileChange();
      if (!this.addFirName) {
        this.type = 'error';
        this.message = '请输入一级类目名称';
        this.isShow = true;
        return;
      } else if (!/^([1-9]\d|\d)$/.test(this.addFirSort)) {
        this.type = 'error';
        this.message = '一级类目排序需要0到99之间';
        this.isShow = true;
        return;
      } else if (this.picError) {
        this.type = 'error';
        this.message = '请输入一级分类图片';
        this.isShow = true;
        return;
      } else {
        this.firAddStatus = true;
        this.addCategorySubmit(this.addFirName, 1, 0, this.addFirSort, this.addFirStatus);
      }
    } else if (level === 2) {
      this.fileChange2();
      if (!this.addSecName) {
        this.type = 'error';
        this.message = '请输入二级类目名称';
        this.isShow = true;
        return;
      }
      if (!this.firId) {
        this.type = 'error';
        this.message = '请先选择一级类目';
        this.isShow = true;
        return;
      } else if (!/^([1-9]\d|\d)$/.test(this.addSecSort)) {
        this.type = 'error';
        this.message = '二级类目排序需要0到99之间';
        this.isShow = true;
        return;
      } else if (this.picError2) {
        this.type = 'error';
        this.message = '请上传二级分类图片';
        this.isShow = true;
        return;
      }
      this.secAddStatus = true;
      this.addCategorySubmit(this.addSecName, 2, this.firId, this.addSecSort, this.addSecStatus);
    } else {
      this.fileChange3();
      if (!this.addThirdName) {
        this.type = 'error';
        this.message = '请输入三级类目名称';
        this.isShow = true;
        return;
      }
      if (!this.firId) {
        this.type = 'error';
        this.message = '请先选择二级类目';
        this.isShow = true;
        return;
      } else if (!/^([1-9]\d|\d)$/.test(this.addThirdSort)) {
        this.type = 'error';
        this.message = '三级类目排序需要0到99之间';
        this.isShow = true;
        return;
      } else if (this.picError3) {
        this.type = 'error';
        this.message = '请上传三级分类图片';
        this.isShow = true;
        return;
      }
      this.thirdAddStatus = true;
      this.addCategorySubmit(this.addThirdName, 3, this.secId, this.addThirdSort, this.addThirdStatus);
    }
  }

  uploadImg1(list, level, text, data) {
    let flag = true;
    this[list].every((val, idx, array) => {
      if (val && val != "pic") {
        flag = false;
        this.adOssUploadService.getSignature2(`/api/v1/common/upload`, '/v1/admin/category/edit_category', val, '')
          .subscribe(res => {
              if (res.code === 200) {
                data['pic'] = res.data[0];
                this.httpService.httpPostAuth(this.addUrl, data)
                  .subscribe(
                    res => {
                      if (res.code == 200) {
                        this.type = 'success';
                        this.message = text;
                        this.isShow = true;
                        this.editModal.hide();
                        switch (level) {
                          case 1:
                            this.firAddStatus = false;
                            this.picList = [];
                            this.fileList = [];
                            this.addFirName = '';
                            this.addFirSort = '';
                            this.addFirStatus = '1';
                            this.getCategoryList(1, 0, 'firLevel');
                            break;
                          case 2:
                            this.secAddStatus = false;
                            this.picList2 = [];
                            this.fileList2 = [];
                            this.addSecName = '';
                            this.addSecSort = '';
                            this.addSecStatus = '1';
                            this.getCategoryList(2, this.firId, 'secLevel');
                            break;
                          case 3:
                            this.thirdAddStatus = false;
                            this.picList3 = [];
                            this.fileList3 = [];
                            this.addThirdName = '';
                            this.addThirdSort = '';
                            this.addThirdStatus = '1';
                            this.getCategoryList(3, this.secId, 'thirdLevel');
                            break;
                        }
                      } else {
                        this.type = 'error';
                        this.message = res.message;
                        this.isShow = true;
                        this.firAddStatus = false;
                        this.secAddStatus = false;
                        this.thirdAddStatus = false;
                      }
                    }
                  );
              }
            }
          );
      }
      return true;
    });
    if (flag) {
      data.pic = data.pic.replace(/h(.*)\.com\//g, '');
      this.httpService.httpPostAuth(this.addUrl, data).subscribe(res => {
        if (res.code === 200) {
          this.type = 'success';
          this.message = text;
          this.isShow = true;
          this.editModal.hide();
          switch (level) {
            case 1:
              this.firAddStatus = false;
              this.picList = [];
              this.fileList = [];
              this.addFirName = '';
              this.addFirSort = '';
              this.addFirStatus = '1';
              this.getCategoryList(1, 0, 'firLevel');
              break;
            case 2:
              this.secAddStatus = false;
              this.picList2 = [];
              this.fileList2 = [];
              this.addSecName = '';
              this.addSecSort = '';
              this.addSecStatus = '1';
              this.getCategoryList(2, this.firId, 'secLevel');
              break;
            case 3:
              this.thirdAddStatus = false;
              this.picList3 = [];
              this.fileList3 = [];
              this.addThirdName = '';
              this.addThirdSort = '';
              this.addThirdStatus = '1';
              this.getCategoryList(3, this.secId, 'thirdLevel');
              break;
          }
        }
      })
    }
  }

  //关闭模态框
  closeModal() {
    this.editModal.hide();
    this.picList4 = [];
    this.fileList4 = [];
    this.isChange = false;
  }


  // 修改类目名称
  editCategory(name: string, id: number, level: number, parent: number, pic, sort, status) {
    this.editName = name;
    this.editId = id;
    this.editLevel = level;
    this.editParent = parent;
    this.editSort = sort;
    this.editStatus = status;
    this.editPic = pic;
    this.picList4 = [];
    this.fileList4 = [];
    if (pic) {
      this.picList4.push({src: pic});
      this.fileList4.push('pic');
      this.canChange = true;
    }
    this.editModal.show();
  }

  // 提交修改类目名称
  editSubmit() {
    const url = `${tuikeSystemUrl}/api/v1/admin/category/edit_category`;
    if (!this.editName) {
      this.type = 'info';
      this.message = '请输入类目名称';
      this.isShow = true;
      return;
    } else if (!/^([1-9]\d|\d)$/.test(this.editSort)) {
      this.type = 'info';
      this.message = '类目排序有误';
      this.isShow = true;
      return;
    } else if (this.picError4) {
      this.type = 'info';
      this.message = '请输入分类图片';
      this.isShow = true;
      return;
    }
    let data = {
      id: this.editId,
      category_name: this.editName,
      level: this.editLevel,
      parent_id: this.editParent,
      sort: this.editSort,
      status: this.editStatus,
      pic: this.editPic
    };
    this.uploadImg1('fileList4', this.editLevel, '修改成功', data);
  }

  promptIsShow(event: any): void {
    this.isShow = event;
  }

  // 删除属性
  delCategory(e, level: number, id: number) {
    e.stopPropagation();
    this.delId = id;
    this.delLevel = level;
    this.delModal.show();
  }

  doDelCateory() {
    if (this.delId > 0) {
      this.delCategoryById();
    }
  }

  delCategoryById() {
    console.log(this.delLevel);
    this.categoryService.delCategory(this.delId).subscribe(res => {
      if (res.code == 200) {
        this.type = 'success';
        this.message = '删除成功';
        this.isShow = true;
        let id = null;
        let type = null;
        switch (this.delLevel) {
          case 1:
            id = 0;
            type = 'firLevel';
            break;
          case 2:
            id = this.firId;
            type = 'secLevel';
            break;
          case 3:
            id = this.secId;
            type = 'thirdLevel';
        }
        this.getCategoryList(this.delLevel, id, type);
      } else {
        this.type = 'error';
        this.message = res.message;
        this.isShow = true;
      }
      this.delModal.hide();
    });
  }

  picError = false;
  picError2 = false;
  picError3 = false;
  picError4 = false;

  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  fileChange2() {
    if (this.fileList2.length == 0 && this.picList2.length == 0) {
      this.picError2 = true;
    } else {
      this.picError2 = false;
    }
  }

  fileChange3() {
    if (this.fileList3.length == 0 && this.picList3.length == 0) {
      this.picError3 = true;
    } else {
      this.picError3 = false;
    }
  }

  fileChange4() {
    this.isChange = true;
    if (this.fileList4.length == 0 && this.picList4.length == 0) {
      this.picError4 = true;
    } else {
      this.picError4 = false;
    }
  }
}
